package com.app.cpcap.lib;

import com.app.cpcap.bean.Usuario;
import com.app.cpcap.vraptor.SistemaController;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.view.Results;

@Intercepts
public class UserInterceptor implements Interceptor{

	private UserAuth user;
	private Result result;
	
	
	
	public UserInterceptor(UserAuth user, Result result) {
		super();
		this.user = user;
		this.result = result;
	}
	

	@Override
	public boolean accepts(ResourceMethod method) {
		return method.containsAnnotation(Restrito.class);
	}

	@Override
	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object instance) throws InterceptionException {
		Usuario usuario = user.getUser();
		if(usuario != null) {
			if(usuario.getAtivo().equals("sim")){
				stack.next(method, instance);
			}
			else{
				result.use(Results.logic()).redirectTo(SistemaController.class).login();
			}
		} else {
			result.use(Results.logic()).redirectTo(SistemaController.class).login();
		}

	}

}
